import os
import webapp2
import jinja2
import logging

from webapp2_extras import i18n

from common import functions

def jinja2_factory(app):
    j = jinja2.Jinja2(app)
    j.environment.filters.update({
        'userstateformat': functions.userstateformat,
        'datetimeformat': functions.datetimeformat,
        'truefalsetoyesnoformat': functions.TrueFalseToYesNoFormat
        # ...
    })
    j.environment.globals.update({
        # Set global variables.
        'uri_for': webapp2.uri_for,
        # ...
    })
    return j

class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def jinja2(self):
#        return jinja2.get_jinja2(factory=jinja2_factory)
        jinja_environment = jinja2.Environment(
                                       loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
                                       extensions=['jinja2.ext.i18n']
                                       )
        jinja_environment.install_gettext_translations(i18n)

        jinja_environment.filters['userstateformat'] = functions.userstateformat
        jinja_environment.filters['datetimeformat'] = functions.datetimeformat
        jinja_environment.filters['truefalsetoyesnoformat'] = functions.TrueFalseToYesNoFormat
        jinja_environment.filters['currencyformat'] = functions.CurrencyFormat
        
        jinja_environment.globals['uri_for'] = webapp2.uri_for
                
        return jinja_environment

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)
        
    def render_template(self, filename, **template_args):
        self.response.write(self.jinja2.render_template(filename, **template_args))
    
    def get_method(self, cls, *args, **kwargs):
        command = kwargs.get('command', 'list')
        method = None
        try:  
            method = getattr(cls, 'op_' + command)
        except:
            self.method_not_implemented()
        if method:
            method(self, *args, **kwargs) # a to oshibki ne vidno :-) 
    
    def method_not_implemented(self):
        template = self.jinja2.get_template('templates/method_not_implemented.html')
        self.response.out.write(template.render(''))
    
    def object_does_not_exist(self):
        template = self.jinja2.get_template('templates/object_does_not_exist.html')
        self.response.out.write(template.render(''))
        
